// Variable init
var i = 0;
var loadimg = "images/loading.gif";
var loadstr = '<div id="load"><img id="load" src="' + loadimg + '" /></div>';
var conf = {};
var pagesregex = /^(forum|topic|user)\/(view|list)(\/(\d+))?/;
var pagelinked = false; // If fp() or tp() are called, this is used to
                        // prevent the page from reloading due to the the hash event trigger
// Grab configuration
function getconf() {
    $.get('index.php?m=conf', function (data) {
        $(data).children("conf").children().each(function () {
            var n = this.tagName;
            conf[n] = {};
            $(this).children().each(function () {
                var v = $(this).text();
                var k = this.tagName;
                v = (v.match(/^(\d+)$/)) ? v * 1 : v;
                conf[n][k] = v;
            });
        });
    });
}
getconf();
// Read cookies
var cookie = function () {
    var ret = {};
    $(document.cookie.split('; ')).each(function () {
        var c = this.split("=");
        ret[c[0].replace("ramble_", "")] = c.slice(1).join("=");
    });
    return ret;
};
function pload() {
    var dialog = $("#dialog").dialog("isOpen");
    var links = (dialog) ? $(".ui-dialog-content a[class!=dialog]") : $("* a[class!=dialog]");
    for (i = 0; i < links.length; i++) {
        var l = $(links[i]);
        var u = l.attr("href");
        if (u) {
            if ((u.indexOf("http://") && u.indexOf("https://") && u.indexOf("ftp://") && u.indexOf("mailto:") && u.indexOf("aim:") && u.indexOf("skype:")) !== -1) {
                continue;
            }
            l.unbind().click(function () {
                var u = $(this).attr("href");
                if (u.slice(0, 1) === "#") {
                    u = u.slice(1);
                }
                if (dialog) {
                    $("#dialog").dialog("close");
                }
                $("#content").lp(u);
                $.history.add(u);
                return false;
            });
            if (u.slice(0, 1) !== "#") {
                l.attr("href", "#" + u);
            }
        }
    }
    links = (dialog) ? $(".ui-dialog-content a.dialog") : $("* a.dialog");
    links.each(function () {
        var u = $(this).attr("href");
        var get = {};
        var s = u.split("?");
        if (s.length > 1) {
            $(s[1].split('&')).each(function () {
                var data = this.split("=");
                get[data[0]] = data[1];
            });
        }
        get.modal = !get.modal; // Not the meaning of modal we mean...
        $(this).unbind().click(function () {
            if (get.width) {
                $("#dialog").dialog("option", "width", Number(get.width));
            }
            if (get.height) {
                $("#dialog").dialog("option", "height", Number(get.height));
            }
            $("#dialog").dialog("option", "modal", true);
            $("#dialog").dialog("option", "closeOnEscape", get.modal);
            $("#dialog").dialog("option", "title", $(this).text());
            if (get.buttons) {
                $("#dialog").dialog("option", "buttons", buttons[get.buttons]);
            }
            else {
                $("#dialog").dialog("option", "buttons", null);
            }
            if (!dialog) {
                $("#dialog").dialog("open");
            }
            $("#dialog").lp(u, function () {
                pload();
            });
            return false;
        });
    });
    // Zebra tables in Firefox (nth-child fix)
    if (navigator.userAgent.indexOf('Webkit') === -1) {
        $(".list tr:nth-child(odd) td").addClass('ztodd');
        $(".list tr:nth-child(even) td").addClass('zteven');
        $(".edit tr:nth-child(odd) td").addClass('ztodd');
        $(".edit tr:nth-child(even) td").addClass('zteven');
        $(".edit tr:nth-child(odd) th").addClass('ztodd');
        $(".edit tr:nth-child(even) th").addClass('zteven');
    }
}
$.fn.lp = function (uri, callback) {
    $(this).html(loadstr);
    if (uri.match(pagesregex)) {
        if ($(this).attr('id') === 'dialog') {
            pages.exec(uri, true);
        } else {
            pages.exec(uri);
            window.location.hash = uri;
        }
    } else {
        var cacheblock = (uri.indexOf('?') !== -1) ? "&" : "?";
        cacheblock += new Date().getTime(); // Stop caching
        if (typeof callback === "function") {
            $(this).load(uri + cacheblock, callback);
        } else {
            $(this).load(uri + cacheblock, function () {
                pload();
                if (!callback && !$(this).attr('class').match('ui-')) {
                    document.cookie = 'ramble_lastpage=' + uri.replace(";", "~~~");
                    window.location.hash = uri;
                }
            });
        }
    }
};
// Pagination
var pp = 15;
$.fn.sidelinks = function (mode, id, page, sl, pages) {
    var u = (mode === "f") ? "forum" : "topic";
    var s = "";
    pages *= 1; // Convert to number
    page *= 1; // Convert to number
    s += (page > 1) ? '<a onclick="' + mode + 'p(' + id + ', 1, ' + sl + ');">' : '<b>';
    s += '&lt;&lt; ';
    s += (page > 1) ? '</a>' : '</b>';
    if (page <= sl) {
        for (i = 1; i < page; i++) {
            s += '<a onclick="' + mode + 'p(' + id + ', ' + i + ', ' + sl + ');">' + i + '</a> ';
        }
    } else {
        for (i = page - sl; i < page; i++) {
            s += '<a onclick="' + mode + 'p(' + id + ', ' + i + ', ' + sl + ');">' + i + '</a> ';
        }
    }
    s += '<b>' + page + '</b>';
    if (page > pages - sl) {
        for (i = page + 1; i <= pages; i++) {
            s += ' <a onclick="' + mode + 'p(' + id + ', ' + i + ', ' + sl + ');">' + i + '</a>';
        }
    } else {
        for (i = page + 1; i <= page + sl; i++) {
            s += ' <a onclick="' + mode + 'p(' + id + ', ' + i + ', ' + sl + ');">' + i + '</a>';
        }
    }
    s += (page < pages) ? '<a onclick="' + mode + 'p(' + id + ', ' + pages + ', ' + sl + ');">' : '<b>';
    s += ' >> ';
    s += (page < pages) ? '</a>' : '</b>';
    s += '<form action="' + u + '.php?m=view;' + id + '&page=' + page + '&pp=' + pp + '&order=asc" onsubmit="' + mode + 'p(' + id + ', $(\'#jump\').val(), ' + sl + '); return false;" id="pjump">';
    s += 'Jump to page <input type="text" value="' + page + '" name="page" id="jump" /> of ' + pages;
    s += '</form>';
    $(this).html(s);
};
function fp(fid, page, sl)
{
    page *= 1; // In case page is passed a string
    sl = (sl) ? sl : 1;
    $('.list tbody').html('<tr><td colspan="4"><div id="load"><img id="load" src="' + loadimg + '" /></div></td></tr>');
    $.get('api.xml?r=forum&fid=' + fid + '&page=' + page + '&pp=' + pp, function (data) {
        if (!data) {
            return false;
        } else {
            $('.list tbody').empty();
        }
        var xml = $(data).children('forum');
        xml.children('topics').children('topic').each(function () {
            var str = "\t\t<tr>\n";
            str += "\t\t\t<td><a href=\"topic/view/" + $(this).children('id').text() + "\">" + $(this).children('title').text() + '</a>';
            var desc = $(this).children('desc').text();
            if (desc) {
                str += "<br /><small>" + desc + "</small>";
            }
            str += "</td>\n";
            var user = $(this).children('user');
            var uname = user.children('name').text();
            var uid = user.children('id').text();
            str += "\t\t\t<td>" + '<a href="user.php?m=view;' + uid + '&amp;height=350px&amp;width=450px" class="dialog">' + uname + "</a></td>\n";
            var r = $(this).children('nposts').text();
            str += "\t\t\t<td class=\"count\">" + ((r) ? r : 0) + "</td>\n";
            var lpost = $(this).children('lp');
            str += "\t\t\t<td>";
            var last = "";
            if (!lpost.text()) {
                last = "No new posts.";
            } else {
                var lpdate = Number(lpost.children('date').text());
                user = lpost.children('user');
                uname = user.children('name').text();
                uid = user.children('id').text();
                last = date("F j, Y g:i:s A", lpdate);
                last += '<br />by <a href="user.php?m=view;' + uid + '&amp;height=350px&amp;width=450px" class="dialog">' + uname + "</a>.";
            }
            str += last + "</td>\n";
            str += "\t\t</tr>\n";
            $('.list tbody').append(str);
        });
        // Renew zebra tables CSS
        $('.list tbody tr:nth-child(even) td').css({backgroundColor: 'rgba(128, 192, 255, 0.1)'});
        $('.list tbody tr:nth-child(odd) td').css({backgroundColor: 'rgba(128, 192, 255, 0.6)'});
        // Page list
        $('#pages').sidelinks("f", fid, page, sl, xml.children('pages').text());
        document.cookie = 'ramble_lastpage=' + 'forum.php?m=view~~~' + fid + '&page=' + page + '&pp=' + pp;
        window.location.hash = 'forum/view/' + fid + '/page=' + page + '/pp=' + pp;
        pagelinked = true;
        pload();
    });
}
function tp(tid, page, sl)
{
    page *= 1; // In case page is passed a string
    sl = (sl) ? sl : 2;
    if (!$('#posts').length) {
        $('.topic #reply').before('<div id="posts"></div>');
    }
    $('#posts').html('<div id="load"><img id="load" src="' + loadimg + '" /></div>');
    $.get('api.xml?r=topic&tid=' + tid + '&page=' + page + '&pp=' + pp + '&order=asc', function (data) {
        if (!data) {
            return false;
        } else {
            $('#posts').empty();
        }
        var xml = $(data).children('topic');
        xml.children('posts').children('post').each(function () {
            var user = $(this).children('user').children();
            var u = {};
            var c = {};
            var n = "";
            user.each(function () {
                var n = this.tagName;
                u[n] = (n === "topics") ? $(this).children('topics').length : $(this).text();
            });
            var ptitle = $(this).children('title').text();
            var pbody = $(this).children('body').text();
            var pdate = Number($(this).children('date').text());
            var pid = $(this).children('id').text();
            var contact = $(this).children('user').children('contact').children();
            contact.each(function () {
                var n = this.tagName;
                var t = $(this).text();
                c[n] = (t !== "") ? t : false;
            });
            var str = "\t\t<div class=\"cont\" id=\"p" + pid + "\">\n";
            str += "\t\t\t<div class=\"userbar\">\n";
            str += "\t\t\t\t<h1><a href=\"user/view/" + u.id + "/dims=350x450\" class=\"dialog\">" + u.name + "</a></h1>\n";
            str += "\t\t\t\t<div class=\"avatar\">\n";
            if (u.avatar) {
                str += "\t\t\t\t\t<img src=\"uploads/avatars/" + u.avatar + "\" />\n";
            }
            str += "\t\t\t\t</div>\n";
            str += "\t\t\t\t<table class=\"contact\">\n";
            str += "\t\t\t\t\t<tr>\n";
            str += "<td><img alt=\"Private Message\" title=\"Private Message\" src=\"images/icons/contact/pm.png\" /></td>\n";
            str += (c.email) ? "<td><a href=\"mailto:" + c.email + "\"><img alt=\"EMail\" title=\"EMail\" src=\"images/icons/contact/email.png\" /></a></td>\n" : "\t\t\t<td />\n";
            str += (c.aim) ? "<td><a href=\"aim:goim?screenname=" + c.aim + "\"><img alt=\"AIM\" title=\"AIM\" src=\"images/icons/contact/aim.png\" /></a></td>\n" : "\t\t\t<td />\n";
            str += (c.msn) ? "<td><a onclick=\"showcont('MSN','" + c.msn + "','p" + pid + "')\"><img alt=\"MSN\" title=\"MSN\" src=\"images/icons/contact/msn.png\" /></a></td>\n" : "\t\t\t<td />\n";
            str += (c.skype) ? "<td><a href=\"skype:" + c.skype + "?chat\"><img alt=\"Skype\" title=\"Skype\" src=\"images/icons/contact/skype.png\" /></a></td>\n" :  "\t\t\t<td />\n";
            str += (c.gtalk) ? "<td><a onclick=\"showcont('GTalk','" + c.gtalk + "','p" + pid + "')\"><img alt=\"Google Talk\" title=\"Google Talk\" src=\"images/icons/contact/gtalk.png\" /></a></td>\n" : "\t\t\t<td />\n";
            str += "\t\t\t\t\t</tr>\n";
            str += "\t\t\t\t</table>\n";
            str += "\t\t\t\t<span class=\"contact_hidden\" id=\"cp" + pid + "\"></span>\n";
            str += "\t\t\t\t<span>Topics: " + u.topics + "</span><br />\n";
            str += "\t\t\t\t<span>Posts: " + u.posts + "</span>\n";
            str += "\t\t\t</div>\n";
            str += "\t\t\t<table class=\"body_cont\">\n";
            str += "\t\t\t\t<tr class=\"info\">\n";
            str += "\t\t\t\t\t<th>" + ptitle + "</th>\n";
            if (u.id === cookie.id || u.rank >= 2) {
                str += "\t\t\t\t\t<th>" + date("F j, Y g:i:s A", pdate) + "</th>\n";
                str += "<th><a onclick=\"edit(" + pid + ",'p');\">[E]</a></th>\n";
            } else {
                str += "\t\t\t\t\t<th colspan=\"2\">" + date("F j, Y g:i:s A", pdate) + "</th>\n";
            }
            str += "\t\t\t\t</tr>\n";
            str += "\t\t\t\t<tr>\n";
            str += "\t\t\t\t\t<td colspan=\"3\" class=\"body\">" + pbody + "</td>\n";
            str += "\t\t\t\t</tr>\n";
            if (u.signature) {
                str += "\t\t\t\t<tr>\n";
                str += "\t\t\t\t\t<td colspan=\"3\" class=\"sig\">" + u.signature + "</td>\n";
                str += "\t\t\t\t</tr>\n";
            }
            str += "\t\t\t</table>\n";
            str += "\t\t</div>\n";
            $('#posts').append(str);
        });
        // Page list
        $('#tpages').sidelinks("t", tid, page, sl, xml.children('pages').text());
        document.cookie = 'ramble_lastpage=topic/view/' + tid + '/page=' + page + '/pp=' + pp + '/order=asc';
        window.location.hash = 'topic/view/' + tid + '/page=' + page + '/pp=' + pp + '/order=asc';
        pagelinked = true;
        pload();
    });
}
// User profiles
function tprev(id)
{
    $('#tprev' + id).slideToggle();
    if ($('#tpa' + id).text() === "v") {
        $('#tpa' + id).text('^');
    }
    else if ($('#tpa' + id).text() === "^") {
        $('#tpa' + id).text('v');
    }
}
// Registration
$.fn.checkVal = function () {
    var id = $(this).attr('id');
    var tval = $(this).val();
    var cval = $('#c' + id).val();
    if (!tval) {
        $('#c' + id).css({borderColor: '#0060FF'});
        return false;
    } else {
        if (cval !== tval) {
            $('#c' + id).css({borderColor: '#FF0000'});
            return false;
        } else if (cval === tval) {
            $('#c' + id).css({borderColor: '#00D000'});
            return true;
        } else {
            return false;
        }
    }
};
function checkReg() {
    if ($('#pass').checkVal() && $('#email').checkVal() && $('#user').val() !== '') {
        $('.ui-dialog-content').html('<div id="load"><img id="load" src="' + loadimg + '" /></div>');
        return true;
    }
    return false;
}
// Userbox
function uboxtoggle() {
    $("#userbox_content").animate({'opacity': 'toggle', 'height': 'toggle'}, function () {
        var cval;
        if ($("#userbox_content")[0].style.display === "none") {
            cval = "show";
            document.cookie = 'ramble_ubox=hide';
            $("#userbox_close a").text('[v]');
        } else {
            cval = "hide";
            document.cookie = 'ramble_ubox=show';
            $("#userbox_close a").text('[^]');
        }
    });
}
// Topics and Posts
function topic_preview() {
    var body = $('#body').val();
    $("#preview").empty().slideUp();
    if (body === "") {
        return false;
    } else {
        $.post("api.php?m=parse", {content: body}, function (data) {
            $("#preview").slideDown('slow').html(data);
            pload(true);
        });
    }
}
function checkreply(data, tid) {
    switch (data) {
    case "":
        $("#replyres").text("There was an error. Try again and maybe something might happen.");
        break;
    case "wrong_session":
        $("#replyres").text("Your sessions don't match up. Are cookies enabled?");
        break;
    case "invalid_post":
        $("#replyres").text("Something isn't matching up in validation. Either someone's up to something or there's a bug you should be reporting.");
        break;
    case "no_body":
        $("#replyres").text("Please enter text for the post body.");
        break;
    default:
        getconf();
        tp(tid, data, conf.topic.sidelinks);
        $("#replyf")[0].reset();
        $("#userbox").lp("index.php?m=ubox", true);
        break;
    }
    return false;
}
function edit(id, mode, close) {
    close = Boolean(close);
    var div = ((mode === "t") ? '#t' : '#p') + id;
    if (!close) {
        $(div + ' .' + mode + 'body').toggle();
        var raw = $(div + ' .' + mode + 'raw');
        raw.toggle();
        var subs = raw.children('form').children('div.subs');
        if (subs.length) {
            subs.remove();
        } else {
            raw.children('form').append('<div class="subs"><input type="submit" value="Update" class="button" /></div>');
        }
    } else {
        subs = $(div + ' div.subs');
        $(div + ' .' + mode + 'raw').hide();
        $(div + ' .' + mode + 'body').show();
        if (subs.length) {
            subs.remove();
        }
        pload();
    }
}
function showcont(cont, value, id) {
    var s = cont + ": " + value;
    $("#c" + id).fadeOut('medium', function () {
        if ($(this).text() !== s) {
            $(this).html(s + "<br />").fadeIn('medium');
        } else {
            $(this).empty();
        }
    });
}
// Init
$(function () {
    pload();
    if (!cookie.lastpage) {
        cookie.lastpage = "forum/list";
    }
    var h = window.location.hash.replace("#", "");
    var lastpage = (h) ? h : cookie.lastpage;
    if (lastpage === "#") {
        lastpage = "forum/list";
    }
    if (lastpage.match(pagesregex)) {
        pages.exec(lastpage);
    }
    else {
        $("#content").lp(lastpage.replace('~~~', ';'));
    }
    var pageregex = /(topic|forum)\.php\?m=view;(\d+)&page=(\d+)&pp=(\d+)/;
    $(window).history(function (e, hash) {
        if (!pagelinked) {
            if (hash.match(pagesregex)) {
                pages.exec(hash);
            }
            else if (hash !== "" && !hash.match(pageregex)) {
                $("#content").lp(hash);
            }
        }
        pagelinked = false;
    });
});